package com.qilin.hscs.hm.mqtt.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.qilin.hscs.hm.convert.DTO2DOConvert;
import com.qilin.hscs.hm.dao.GroupTargetRepository;
import com.qilin.hscs.hm.dao.SceneRepository;
import com.qilin.hscs.hm.dto.SceneBaseInfoAlterDto;
import com.qilin.hscs.hm.dto.SceneDto;
import com.qilin.hscs.hm.enums.GroupTypeEnum;
import com.qilin.hscs.hm.mqtt.service.SenceService;
import com.qilin.hscs.hm.mqtt.service.common.ServiceCommon;
import com.qilin.hscs.hm.pojo.GroupTarget;
import com.qilin.hscs.hm.pojo.Scene;
import com.qilin.hscs.hm.strategy.FieldStrategy;
import com.qilin.hscs.hm.util.MqttResultUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by 10188 on 2018/4/28.
 */
@Service("scene")
@Transactional
public class SenceServiceImpl extends ServiceCommon implements SenceService {

    @Autowired
    private SceneRepository repository;

    @Autowired
    private GroupTargetRepository groupTargetRepository;

    private static final Logger logger= LogManager.getLogger(SenceServiceImpl.class.getName());

    @Override
    public void findTotalSence() {
        List<Scene> scenes = repository.findAll();
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("phone",phone);
        data.put("scenes", scenes);
        msg=MqttResultUtil.getResult(9001, 0, data);
    }

    @Override
    public void addSence() {
        JSONObject sceneObj = dataObj.getJSONObject("scene");
        SceneDto sceneDto = sceneObj.toJavaObject(SceneDto.class);
        Scene scene = DTO2DOConvert.SceneDto2Sence(sceneDto);
        GroupTarget groupTarget=new GroupTarget();
        List<GroupTarget> groupTargets = groupTargetRepository.findAll();
        List<Integer> glds = groupTargets.stream().map(e -> e.getGld()).collect(Collectors.toList());
        int gld = FieldStrategy.gIdStrategyCreate(glds);
        groupTarget.setGld(gld);
        groupTarget.setType(GroupTypeEnum.SCENE.getType());
        GroupTarget re = groupTargetRepository.save(groupTarget);
        if (re != null) {
            scene.setGld(gld);
            Scene sceneRe = repository.save(scene);
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("phone",phone);
            data.put("scene", sceneRe);
            msg=MqttResultUtil.getResult(9002, 0, data);
        }
    }

    @Override
    public void alterSence() {
        JSONObject sceneObj = dataObj.getJSONObject("scene");
        SceneBaseInfoAlterDto baseInfoAlterDto = sceneObj.toJavaObject(SceneBaseInfoAlterDto.class);
        Scene one = repository.findOne(baseInfoAlterDto.getId());
        BeanUtils.copyProperties(baseInfoAlterDto, one);
        Scene re = repository.save(one);
        if (re != null) {
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("phone",phone);
            data.put("scene", re);
            msg=MqttResultUtil.getResult(9003, 0, data);
        }
    }

    @Override
    public void delSence() {
        Integer id = dataObj.getInteger("id");
        //todo
    }
    @Override
    public void handle() {
        switch (cmd) {
            case 8001:
                findTotalSence();
                isflushToGateway(false);
                flush();
                break;
            case 8002:
                addSence();
                isflushToGateway(false);
                flush();
                break;
            case 8003:
                alterSence();
                isflushToGateway(false);
                flush();
                break;
            case 8004:
                delSence();
                isflushToGateway(false);
                flush();
                break;
            default:
        }
    }

    @Override
    public void initailData() {
        try {
            msgObj = JSON.parseObject(msg);
            dataObj = msgObj.getJSONObject("data");
        } catch (JSONException je) {
            logger.warn("传输过来的json字符串有误，主机无法解析 错误详细情况为={}", je.getStackTrace());
        }
        cmd = msgObj.getInteger("cmd");
        if (topicVar != null) {
            if (!topicVar.contains("/rsp")) {
                phone = msgObj.getString("phone");
            }
        }
    }
}
